package com.hengxinguotong.zhihuichengjian.ui.quality;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.RectificationListAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.SecurityRectificationListAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.Quality;
import com.hengxinguotong.zhihuichengjian.bean.QualityListRes;
import com.hengxinguotong.zhihuichengjian.bean.Security;
import com.hengxinguotong.zhihuichengjian.bean.SecurityListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.ui.PersonLiableListActivity;
import com.hengxinguotong.zhihuichengjian.ui.security.SecurityRectificationActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/7/11.
 */

public class RectificationListFragment extends BaseFragment implements View.OnClickListener{

    private View rootView = null;
    public RectificationListActivity mActivity;
    private String createBy = null;

    @BindView(R.id.rectification_lv)
    public PullToRefreshListView rectificationLv;
    @BindView(R.id.et_project)
    HXTextView etProject;

    private RectificationListAdapter rectificationListAdapter;
    private SecurityRectificationListAdapter securityRectificationListAdapter;
    private int pageIndex = 1;
    private List<Quality> qualities;
    private List<Security> securities;
    private String state = "1";//1:待受理; 2:处理中;3:待检查;4:检查不通过；5:已完成
    private int type;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case Constants.QUALITY:
                case Constants.QUALITY_SUPERVISE:
                    List<Quality> qualityDatas = (List<Quality>) msg.obj;
                    addQualityData(qualityDatas);
                    break;
                case Constants.SECURITY:
                case Constants.SECURITY_SUPERVISE:
                case Constants.CIVILIZED_CONSTRUCTION_SUPERVISE:
                    List<Security> securityDatas = (List<Security>) msg.obj;
                    addSecurityData(securityDatas);
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt("type");
            state = getArguments().getString("state");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_rectification_list, null);
            ButterKnife.bind(this, rootView);
            mActivity = (RectificationListActivity) getActivity();
            switch (type){
                case Constants.QUALITY:
                case Constants.QUALITY_SUPERVISE:
                    qualities = new ArrayList<>();
                    rectificationListAdapter = new RectificationListAdapter(qualities, mActivity);
                    rectificationLv.setAdapter(rectificationListAdapter);
                    break;
                case Constants.SECURITY:
                case Constants.SECURITY_SUPERVISE:
                case Constants.CIVILIZED_CONSTRUCTION_SUPERVISE:
                    securities = new ArrayList<>();
                    securityRectificationListAdapter = new SecurityRectificationListAdapter(securities, mActivity);
                    rectificationLv.setAdapter(securityRectificationListAdapter);
                    break;
            }
            setListener();
        }else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onLazyLoad() {
        handler.postDelayed(MyRunnable, 500);

    }

    Runnable MyRunnable = new Runnable() {
        @Override
        public void run() {
            rectificationLv.setRefreshing();
        }
    };

    @Override
    public void onStart() {
        super.onStart();
//        handler.postDelayed(MyRunnable, 500);
    }

    public void reLoad(){
        if(rectificationLv != null){
            handler.postDelayed(MyRunnable, 500);
        }
    }

    public static RectificationListFragment newInstance(int type, String state){
        Bundle bundle = new Bundle();
        bundle.putInt("type",type);
        bundle.putString("state", state);
        RectificationListFragment fragment = new RectificationListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    private void setListener(){
        rectificationLv.setMode(PullToRefreshBase.Mode.BOTH);
        rectificationLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(type == Constants.QUALITY||type == Constants.QUALITY_SUPERVISE) {
//                    pushMsg(type, qualities.get(position - 1));
                    Intent intent = new Intent(mActivity, RectificationActivity.class);
                    intent.putExtra("type", type);
                    intent.putExtra("state", state);
                    intent.putExtra("quality", qualities.get(position - 1));
                    startActivityForResult(intent, RectificationListActivity.UPDATE);
                } else {
                    Intent intent = new Intent(mActivity, SecurityRectificationActivity.class);
                    intent.putExtra("type", type);
                    intent.putExtra("security", securities.get(position - 1));
                    startActivityForResult(intent, RectificationListActivity.UPDATE);
                }

            }
        });

        rectificationLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getcRectificationInfo(null);
                mActivity.getRectificationCount();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getcRectificationInfo(null);
            }
        });
    }

    private void pushMsg(int type, Quality quality){

        RequestParams params = new RequestParams();
        params.addBodyParameter("userName", SPUtil.getString(mActivity, "realName"));
        params.addBodyParameter("constructionId", SPUtil.getString(mActivity, "constructionid"));
        params.addBodyParameter("type", type + "");//类型.1:质量检查;2:安全检查;3:日常安全检查（目前为传1）
        params.addBodyParameter("createBy", quality.getCreateBy());
        params.addBodyParameter("inspectionId", quality.getId());//从消息列表跳转消息状态 1未读 0已读（从消息列表跳转时传否则不传）
        Utils.requestData(null, mActivity, "/inspection/pushMsg/" + SPUtil.getString(mActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(Utils.isEmpty(json)){
                    return;
                }
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    String msg = object.getString("msg");
                    if(status == 0){
                        Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void getcRectificationInfo(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            String constructionid = SPUtil.getString(mActivity, "constructionid");
            jsonObject.put("constructionId", constructionid);
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("processingOpinion", "3");
            jsonObject.put("correctiveStatus", state);
            if (!hasList()) {
                jsonObject.put("contactId", SPUtil.getString(mActivity, "userId"));
            }
            jsonObject.put("type", type);
            if(createBy != null){
                jsonObject.put("createBy", createBy);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, mActivity, "/inspection/queryByConstructionId/" + SPUtil.getString(mActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (rectificationLv.isRefreshing()) {
                    rectificationLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    Message msg = handler.obtainMessage();
                    msg.what = type;
                    if(type == Constants.QUALITY||type == Constants.QUALITY_SUPERVISE){
                        QualityListRes qualityListRes = gson.fromJson(json, QualityListRes.class);
                        msg.obj = qualityListRes.getValue();
                    }else{
                        SecurityListRes securityListRes = gson.fromJson(json, SecurityListRes.class);
                        msg.obj = securityListRes.getValue();
                    }
                    msg.sendToTarget();
                }else{
                    showEmptyView(rectificationLv);
                }
            }

            @Override
            public void onFailure(String json) {
                if (rectificationLv.isRefreshing()) {
                    rectificationLv.onRefreshComplete();
                }
                showEmptyView(rectificationLv);
            }
        });
    }

    private void addQualityData(List<Quality> datas) {
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(rectificationLv);
            }else{
                dismissEmptyView();
            }
            qualities = datas;
            if (datas.size() == Utils.ONCECOUNT) {
                rectificationLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            qualities.addAll(datas);
        }
        rectificationListAdapter.setDatas(qualities);
        if (datas.size() < Utils.ONCECOUNT) {
            rectificationLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    private void addSecurityData(List<Security> datas) {
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(rectificationLv);
            }else{
                dismissEmptyView();
            }
            securities = datas;
            if (datas.size() == Utils.ONCECOUNT) {
                rectificationLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            securities.addAll(datas);
        }
        securityRectificationListAdapter.setDatas(securities);
        if (datas.size() < Utils.ONCECOUNT) {
            rectificationLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    @OnClick({R.id.search_ll, R.id.iv_p, R.id.et_project})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_ll:
            case R.id.iv_p:
            case R.id.et_project:
                Intent intent = new Intent(mActivity, PersonLiableListActivity.class);
                intent.putExtra("type", 0);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            if(requestCode == 1 && resultCode == 1){
                User user = (User) data.getSerializableExtra("selectUser");
                createBy = user.getUserId();
                etProject.setText(user.getName());
                reLoad();
            }
            if(requestCode == RectificationListActivity.UPDATE){
                reLoad();
            }
        }
    }
}
